#!/bin/bash
# ****************************************************
# *  ____                                            *
# * / ___|  ___  _ __  _   _                         *
# * \___ \ / _ \| '_ \| | | |                        *
# *  ___) | (_) | | | | |_| |                        *
# * |____/ \___/|_| |_|\__, |                        *
# *                    |___/                         *
# *                                                  *
# * Copyright (c) 2012 Sony Mobile Communications AB *
# ****************************************************
#
#
#
LOGPID=$$
CURRENTPATH=`pwd`
#==================================================================================
#
#	Name:		createLogDirectory 
#	Description:	Create directories. Set work folder.
#	Parameter 1:	NA
#	Returns:	NA
#	Notes:		Added by 23048971 to clean up the code in the main loop.
#	Created:	2010-10-06
#
#==================================================================================
function createLogDirectory {	
  NOW="`date +%y%m%d_%H%M%S`"							# Returning date and time
  NOWDATE="`date +%Y%m%d`"							# Returning date and time for spank logs

  LOGSDIR="ATlog-${NOW}"
  if [ "$EXACTSERIAL" != "" ]; then 						# Support multiple devices
    LOGSDIR="${LOGSDIR}-$EXACTSERIAL"
  fi
  LOGSDIR="$LOGSDIR/"

  if [ ! -d $NOWDATE ]; then							# Directory to store logs     YYYYMMDD/Spanklogs-
    mkdir $NOWDATE
  fi

  cp $SPANKCONFIGFILE $NOWDATE

  cd $NOWDATE
  mkdir $LOGSDIR
  
  mv $SPANKCONFIGFILE $LOGSDIR

  CURRENTLOGPATH="$CURRENTPATH/$NOWDATE/$LOGSDIR"
  echo "---------------"
  echo "All logs will be placed in this folder: "
  echo "     $LOGSDIR "
  echo "Complete path: "
  echo "     $CURRENTLOGPATH"
  echo "---------------"

}
#===    Function	===========================================================
#
#	Name:		checkAdb
#	Description:	The function checks if the path to adb directory is correct -
# 			In case path is not specified, the default path is selected by spank
#	Parameter 1:	NA
#	Created:	2009-12-15
#
#==================================================================================
function checkAdb {
    if [ ! -z "$JENKINS_URL" ]; then
        if [ ! -f "/usr/bin/adb" ]; then
            echo "ERROR: since JENKINS_URL=<$JENKINS_URL> and /usr/bin/adb is not a file"
            exit
        fi
        ADB="/usr/bin/adb"
    else
        if [ ! -d "$ADBDIR" ]; then
            ADB_IN_PATH=$(adb version)
            echo ""
            echo "ADB_IN_PATH: $ADB_IN_PATH"
            echo ""
            if [ "$ADB_IN_PATH" = "" ]; then
                echo ""
                echo "Error: Cannot locate adb. Please set ANDROIDSDK_HOME ($ANDROIDSDK_HOME)"
                echo "or make sure adb is in your path"
                echo
                echo "Howto:"
                echo "export ANDROIDSDK_HOME=<path_to_Android_SDK>"
                echo
                exit
            else
                ADB=adb
            fi
        fi
    fi

    if [ "$DEVICESERIAL" != "" ]; then
      MYTEMP=$($ADB devices | grep $DEVICESERIAL)
      NOOFMATCHES=$($ADB devices | grep -c $DEVICESERIAL)
      if [ "$NOOFMATCHES" != "1" ]; then
        echo "*** ERROR *** No match/not unique. Found $NOOFMATCHES matches for $DEVICESERIAL"
        exit 1
      fi

      EXACTSERIAL=$(echo ${MYTEMP%d*})				# Split line on 'd' to remove 'device'

      if [ "$EXACTSERIAL" != "" ]; then
        ADB="$ADB -s $EXACTSERIAL"
      else
        echo "*** ERROR *** No device matches $DEVICESERIAL"	# If no unique device found
        exit 1
      fi

    fi

    SH="$ADB shell"						# Setting variable for adb
}

#===    Function	===========================================================
#
#	Name:		startLogOfDevice
#	Description:	Extracting logs from device
#	Parameter 1:	NA
#	Returns:	NA
#	Notes:		Start logging the device. Function created to clean up main loop
#	Created:	2010-10-06
#
#==================================================================================
function startLogOfDevice {  
  echo "* starting logging "
#  MONKEY_FILENAME=${LOGSDIR}monkey_s${SEED}.txt  			# Monkey log in text format for every seed
  LOGCAT_FILENAME=${LOGSDIR}logcat.txt  			# Logcat in text format for every seed
  RADIO_FILENAME=${LOGSDIR}radio.txt  				# Logcat (radio) in text format for every seed
  KERNEL_FILENAME=${LOGSDIR}kernel.txt				# Logcat (radio) in text format for every seed
  EVENTS_FILENAME=${LOGSDIR}events.txt             		# Logcat (events) in text format for every seed
  BUGREPORT_FILENAME=${LOGSDIR}bugreport.txt  			# Bug report in text format for every seed
  ANR_FILENAME="${LOGSDIR}anr_traces.txt"
  DEBUG_FILENAME="${LOGSDIR}debug.txt"
  ATCLOGCAT="${LOGSDIR}ATCLOG.txt"
 ATCUIAUTOLOG=${LOGSDIR}uiautomatior-log.txt
#  FOOTPRINTS_FILENAME=${LOGSDIR}event_footprints_s${SEED}.txt

  $ADB root
#  $SH cat /proc/kmsg > $KERNEL_FILENAME &      		      		# Start and printing kernel log in background
  $ADB logcat -c &
  $ADB logcat -v threadtime > $LOGCAT_FILENAME &            		# Start and printing logcat in background
  $ADB logcat -v threadtime -b radio > $RADIO_FILENAME &    		# Start and printing logcat (radio prints) background
  $ADB logcat -v threadtime -b events > $EVENTS_FILENAME &  		# Start and printing logcat (events prints) background
}


#===    Function	===========================================================
#
#	Name:		echohtml
#	Description:	echo to html file
#	Parameters:	$@ String that contains html formatted text.
#	Returns:	NA
#	Created:	2010-02-10
#
#==================================================================================
function echohtml {
  echo "$@" >> ${LOGSDIR}"spank_log.html"
}


#===    Function	===========================================================
#
#	Name:		echohtmldivider
#	Description:	simple colorful divider in the page
#	Returns:	NA
#	Created:	2010-02-10
#
#==================================================================================
function echohtmldivider {
  echohtml "<FONT COLOR="DARKRED">****************************************************************************************</FONT><br>"
}


#===    Function	===========================================================
#
#	Name:           CreateSpankHTMLLog
#	Description:    Create a HTML log
#	Parameter 1:	NA
#	Returns:        NA
#	Created:	2010-02-10
#
#==================================================================================
function CreateSpankHTMLLog {
  echohtml "<html><head>" 
  echohtml "<title>SPANK LOG $EXTRACTEDHW $EXTRACTEDSW</title>" 
  echohtml "<META HTTP-EQUIV="refresh" CONTENT="300">"				# AUTOMATIC REFRESH EVERY 2 MINUTES ( 120 Secs )
  echohtml "</head>"
  echohtml "<body BGCOLOR="LAVENDER">"
  echohtml "<br><BIG><BIG><B>SPANK</BIG></BIG></B><br><br>"
  echohtml "(Automatic refresh every 5 min)"
  echohtml "<br>"
  echohtml "<a href=""https://wiki.sonyericsson.net/androiki/Spank"">The Spank Wiki</A><br>"
  echohtml "<br>"
  echohtml "<a href="$DEVICEUNDERTESTPROPS">The Device under test (properties)</A><br>"
  echohtml "<br>"
}


#===    Function	===========================================================
#
#	Name:           echohtmlTable
#	Description:    Add from two parameters into a simple table
#	Parameter:
#			$1 Long string that should be formatted for HTML output.
#	Returns:        NA
#	Created:	2010-02-10
#
#==================================================================================
function echohtmlTable {

  TABLEFIELD="`echo "$1" | sed 's/[\r\n]/<br>/g'`"		# Replace /R/N with <br> g = global (all occurances)

  echohtml "" 
  echohtml "<table border=""1"" width=""95%"">"
  echohtml "<tr>"
  echohtml "<td>" 
  #echohtml "<FONT COLOR="FORESTGREEN">"$TABLEFIELD"</FONT><br>"
  echohtml "<FONT COLOR="BLACK">"$TABLEFIELD"</FONT><br>"
  echohtml "</td>"
  echohtml "</tr>" 
  echohtml "</table>"
}



function postRunDataExtraction {
  echo "----------------------------------------------------"
  echo " post run data extraction from attached device "
  echo " "
  echo " dropbox data:"
  $ADB pull /data/system/dropbox ${LOGSDIR}/data-dropbox
  echo " "
  echo " bugreports from sdcard:"
  $ADB pull /mnt/sdcard/BugReport ${LOGSDIR}/mnt-sdcard-bugreport
  echo " "
  echo " data misc folder:"
  $ADB pull /data/misc ${LOGSDIR}/data-misc

  echo "----------------------------------------------------"
}

#===    Function	===========================================================
#
#	Name:           extractHprofFiles
#	Description:    extract hprof files from phone FS
#	Parameter 1:	NA
#	Returns:        NA
#
# 	adb pull /data/misc/outofmemory0.hprof sNNN-outofmemory0.hprof
# 	adb shell rm /data/misc/outofmemory0.hprof
# 	do this for 0,1,2,3 hprof files to cover possible case with multiple files.
#
#==================================================================================
function extractHprofFiles {
  echo "----------------------------------------------------"
  echo "* extract HPROF files - begin              (error prints might appear below if files does not exist, that is ok)" 

  $ADB root
  #$ADB pull /data/misc ${LOGSDIR}/data-misc

  echo "*"

  $ADB pull /mnt/sdcard/outofmemory0.hprof ${LOGSDIR}/outofmemory0.hprof
  $ADB pull /mnt/sdcard/outofmemory1.hprof ${LOGSDIR}/outofmemory1.hprof
  $ADB pull /mnt/sdcard/outofmemory2.hprof ${LOGSDIR}/outofmemory2.hprof
  $ADB pull /mnt/sdcard/outofmemory3.hprof ${LOGSDIR}/outofmemory3.hprof
  $ADB pull /mnt/sdcard/outofmemory4.hprof ${LOGSDIR}/outofmemory4.hprof
  $ADB pull /mnt/sdcard/outofmemory5.hprof ${LOGSDIR}/outofmemory5.hprof
  $ADB pull /mnt/sdcard/outofmemory6.hprof ${LOGSDIR}/outofmemory6.hprof
  $ADB pull /mnt/sdcard/outofmemory7.hprof ${LOGSDIR}/outofmemory7.hprof
  $ADB pull /mnt/sdcard/outofmemory8.hprof ${LOGSDIR}/outofmemory8.hprof
  $ADB pull /mnt/sdcard/outofmemory9.hprof ${LOGSDIR}/outofmemory9.hprof

  echo "*"

  $SH ls /mnt/sdcard/*.hprof

  $SH rm /mnt/sdcard/outofmemory0.hprof
  $SH rm /mnt/sdcard/outofmemory1.hprof
  $SH rm /mnt/sdcard/outofmemory2.hprof
  $SH rm /mnt/sdcard/outofmemory3.hprof
  $SH rm /mnt/sdcard/outofmemory4.hprof
  $SH rm /mnt/sdcard/outofmemory5.hprof
  $SH rm /mnt/sdcard/outofmemory6.hprof
  $SH rm /mnt/sdcard/outofmemory7.hprof
  $SH rm /mnt/sdcard/outofmemory8.hprof
  $SH rm /mnt/sdcard/outofmemory9.hprof

  echo "* extract HPROF files - done" 
  echo "----------------------------------------------------"
}


#===    Function	===========================================================
#
#	Name:           afterMonkeyEnded
#	Description:    Collects some data, sets some parameters after monkey stopped.
#	Parameter 1:	NA
#	Returns:        NA
#
#==================================================================================
function afterMonkeyEnded {
  spankToolDebugLog "afterMonkeyEnded."
#  echo `date`" - Monkey ended"
  echohtml "<FONT COLOR="BLUE">`date` - Monkey ended</FONT><br>"
  $SH logwrapper "MONKEY ENDING TAG"
  #MONKEYRUNS=""
  RUNTIME_STOP=`date +%s`  						# Start/stop time formatting for spank report
  RUNTIME_TEST=$((RUNTIME_STOP-RUNTIME_START))
  RUNTIME_TOTAL=$((RUNTIME_TOTAL+RUNTIME_TEST))

  echo ""
  echo ""
  echo "sleep 7..."
  sleep 7

  echo ""
  echo "sleep 2..."
  sleep 2
  echo "* extracting bugreport"
  $ADB bugreport > $BUGREPORT_FILENAME			# for debugging. sometimes is the bugreport empty, why? 20121018 23048971
  echo ""

  #getDuration $RUNTIME_TEST  						# Formatting duration for test run
  #seedTime=$DURATION
  getDuration $RUNTIME_TOTAL
  echo "----------------------------------------------------"
  #echo "Test Runtime: $seedTime "
  #echo "Total Runtime: $DURATION"
  echo "----------------------------------------------------"
  #echohtml "Test Runtime: $seedTime (Total: $DURATION)<br>"			
  #spankToolDebugLog "afterMonkeyEnded. Test Runtime: $seedTime (Total: $DURATION)"
  echo ""
}

function clean_up {
  echo "Clean up ..." 
  #Kill all children
  for _pid in `ps --ppid $LOGPID | sed '1d' | awk '{print $1}'`
  do
    if [ -n "`ps --pid $_pid | sed '1d'`" ];
    then
      kill $_pid
    fi
  done
  #rm $LOG_FILE
  exit 1
}


#===    Function	===========================================================
#
#	Name:		parseInformationFromLogFilesAndPresentResult
#	Description:	Printing out the spank settings
#	Parameter 1:	NA
#	Returns:	NA
#	Notes:		Added by 23048971
#	Created:	2010-06-15
#
#==================================================================================
function parseInformationFromLogFilesAndPresentResult {
  #spankToolDebugLog "parseInformationFromLogFilesAndPresentResult."
  echo ""
  echo "----------------------------------------------------"
  echo "Collecting data for analysis..."

  EACTIVITYMANAGER_TEXT=`grep "E ActivityManager" "$LOGCAT_FILENAME"`			# Better ANR Prints
  echo " " >> $DEBUG_FILENAME
  echo "EACTIVITYMANAGER_TEXT" >> $DEBUG_FILENAME
  echo "$EACTIVITYMANAGER_TEXT" >> $DEBUG_FILENAME
  
  ###################
  ATCLOG=`grep "ATCAutoTest" "$LOGCAT_FILENAME"`
  echo "" >> $ATCLOGCAT
  echo "$ATCLOG" >> $ATCLOGCAT
  ####################
  ED3ANR_TEXT=`grep -A 40 "Application is not responding:" "$LOGCAT_FILENAME"`		# ADR info for ED3
  echo " " >> $DEBUG_FILENAME
  echo "ED3ANR_TEXT" >> $DEBUG_FILENAME
  echo "$ED3ANR_TEXT" >> $DEBUG_FILENAME
  ANR_ANNOTATION=`grep "Annotation:" "$LOGCAT_FILENAME"`				# ANR. ANNOTATION
  echo " " >> $DEBUG_FILENAME
  echo "ANR_ANNOTATION" >> $DEBUG_FILENAME
  echo "$ANR_ANNOTATION" >> $DEBUG_FILENAME
  ANRTOTAL=`grep " TOTAL:" "$LOGCAT_FILENAME"`						# ANR. TOTAL CPU USAGE
  echo " " >> $DEBUG_FILENAME
  echo "ANRTOTAL" >> $DEBUG_FILENAME
  echo "$ANRTOTAL" >> $DEBUG_FILENAME
  ANRLOAD=`grep " Load:" "$LOGCAT_FILENAME"`						# ANR. CPU LOAD
  echo " " >> $DEBUG_FILENAME
  echo "ANRLOAD" >> $DEBUG_FILENAME
  echo "$ANRLOAD" >> $DEBUG_FILENAME
  WATCHDOGKILLING=`grep "WATCHDOG KILLING" "$LOGCAT_FILENAME" | cut -d':' -f5`		# MOST LIKELY A SYSTEMCRASH INDICATED IN LOGCATLOG
  echo " " >> $DEBUG_FILENAME
  echo "ANRREASON" >> $DEBUG_FILENAME
  echo "$ANRREASON" >> $DEBUG_FILENAME
  ANRREASON=`grep "Reason: " "$LOGCAT_FILENAME" | cut -d' ' -f12`			# ANR. REASON    -d = delimiter, f = field
  echo " " >> $DEBUG_FILENAME
  echo "ANRREASON" >> $DEBUG_FILENAME
  echo "$ANRREASON" >> $DEBUG_FILENAME
  ANRPREVDISP=`grep ": Previous dispatch state:" "$LOGCAT_FILENAME"`			# ANR. PREVIOUS DESPATCH STATE
  echo " " >> $DEBUG_FILENAME
  echo "ANRPREVDISP" >> $DEBUG_FILENAME
  echo "$ANRPREVDISP" >> $DEBUG_FILENAME
  ANRCURRDISP=`grep ": Current dispatch state:" "$LOGCAT_FILENAME"`			# ANR. CURRENT DISPATCH STATE
  echo " " >> $DEBUG_FILENAME
  echo "ANRCURRDISP" >> $DEBUG_FILENAME
  echo "$ANRCURRDISP" >> $DEBUG_FILENAME
  ANRCURR=`grep ": Current state:" "$LOGCAT_FILENAME"`					# ANR. CURRENT STATE
  echo " " >> $DEBUG_FILENAME
  echo "ANRCURR" >> $DEBUG_FILENAME
  echo "$ANRCURR" >> $DEBUG_FILENAME
  ANRDISP=`grep ": Dispatch state:" "$LOGCAT_FILENAME"`					# ANR. DISPATCH STATE
  echo " " >> $DEBUG_FILENAME
  echo "ANRDISP" >> $DEBUG_FILENAME
  echo "$ANRDISP" >> $DEBUG_FILENAME
  LASTDIEDPROC=`grep died. "$LOGCAT_FILENAME" | tail` 					# ANR. LAST 10 PROCESSES DIED JUST BEFORE ANR
  echo " " >> $DEBUG_FILENAME
  echo "LASTDIEDPROC" >> $DEBUG_FILENAME
  echo "$LASTDIEDPROC" >> $DEBUG_FILENAME
  LASTLOGCATROWS=`tail "$LOGCAT_FILENAME"`						# LAST ROWS OF LOGCAT LOG
  echo " " >> $DEBUG_FILENAME
  echo "LASTLOGCATROWS" >> $DEBUG_FILENAME
  echo "$LASTLOGCATROWS" >> $DEBUG_FILENAME
  NATIVECRASHINFO=`grep -A 20 ": Build fingerprint:" "$LOGCAT_FILENAME"` 		# NATIVE. GET INFORMATION RELATED TO NATIVE CRASHES
  echo " " >> $DEBUG_FILENAME
  echo "NATIVECRASHINFO" >> $DEBUG_FILENAME
  echo "$NATIVECRASHINFO" >> $DEBUG_FILENAME
  NATIVECRASHMOREDETAILS=`grep "I DEBUG   : pid:" $LOGCAT_FILENAME | cut -d':' -f7- | sed 's/ /_/g'`	# NATIVE. GET SHORT DETAILS OF WHAT PROCESS IS THE BAD GUY 20120114.emil. fixed nicer prints 
# debugging...  emil 20121018
  NATIVECRASHDETAILS=`grep "I DEBUG   : pid:" $LOGCAT_FILENAME | cut -d' ' -f22 | sed 's/ /_/g'`	# NATIVE. GET SHORT DETAILS OF WHAT PROCESS IS THE BAD GUY 20120114.emil. fixed nicer prints 
# debugging...  emil 20121005

  echo " " >> $DEBUG_FILENAME
  echo "NATIVECRASHDETAILS" >> $DEBUG_FILENAME
  echo "$NATIVECRASHDETAILS" >> $DEBUG_FILENAME
  CRASHDETAILS=`grep -A 20 "FATAL EXCEPTION:" "$LOGCAT_FILENAME"`			# Get some Crash details from logcat log.
  echo " " >> $DEBUG_FILENAME
  echo "CRASHDETAILS" >> $DEBUG_FILENAME
  echo "$CRASHDETAILS" >> $DEBUG_FILENAME
  UNCAUGHTEXCEPTION=`grep "uncaught exception" "$LOGCAT_FILENAME" `			# Uncaught Exception?
  echo " " >> $DEBUG_FILENAME
  echo "UNCAUGHTEXCEPTION" >> $DEBUG_FILENAME
  echo "$UNCAUGHTEXCEPTION" >> $DEBUG_FILENAME


  echo "* Data collected... "
  cat $EVENTS_FILENAME >> $EVENTSTATISTICSFILE						# Merge the eventslog info the EVENTSTATISTICSFILE that contains RAW testdata
 

  SHORTLOGCAT_FILENAME=${LOGSDIR}shortlogcat.txt  				
  `tail -n 1000 "$LOGCAT_FILENAME" > $SHORTLOGCAT_FILENAME`				# Short Logcat
  
  echo "* Analyzing..."
    UIAUTO_SUMMARY1=`grep "FAILURES!!!" "$ATCUIAUTOLOG"`
  UIAUTO_SUMMARY1=`grep "Tests run:" "$ATCUIAUTOLOG"`
 echohtml "<br> Summary </br>"
  echohtml "<FONT COLOR="RED"><br> $UIAUTO_SUMMARY1 </br></font>"
  echohtml "<br> $UIAUTO_SUMMARY2 </br>"
    echohtml "<br>"
    echohtml "<br>"
    echohtml "<br>"
  #UIAUTO_FAILURE=`grep "Failure in" "$ATCUIAUTOLOG"`
  #echohtml "<FONT COLOR="RED"<br> $UIAUTO_FAILURE </br></font>"
  #UIAUTO_ERROR=`grep "Error in" "$ATCUIAUTOLOG"`
  #echohtml "<FONT COLOR="RED"><br> $UIAUTO_ERROR </br></font>"
  parseUiAutoLog
  echo
  echo "----------------------------------------------------"
  echo ""
}
#===    Function	===========================================================
function parseUiAutoLog {
    ATCUIAUTOLOG=${LOGSDIR}uiautomatior-log.txt
    if [ ! -f $ATCUIAUTOLOG ]; then
      echo "$ATCUIAUTOLOG : does not exists"
              exit 1
     elif [ ! -r $ATCUIAUTOLOG ]; then
          echo "$ATCUIAUTOLOG: can not read"
          exit 2
    fi
    
    if [ ! -f ${LOGSDIR}ATCLOG.txt ]; then
      echo "${LOGSDIR}ATCLOG.txt : does not exists"
              exit 1
     elif [ ! -r ${LOGSDIR}ATCLOG.txt ]; then
          echo "${LOGSDIR}ATCLOG.txt: can not read"
          exit 2
    fi
    while read line
    do
        #
        echohtmlTable "`echo $line | awk '{print $7 $8 $9 $10}'`"
        #echohtmlTable "<b>Test Name:</b><br> `echo $line | awk '{print $8}'`<br>"
    done < ${LOGSDIR}ATCLOG.txt

	ATCERRORLOG="Error in"
	ATCFAILURELOG="Failure in"
    while read line
    do
        
		if [ ${#TEMPLINE1} -ne 0 ]; then            
            echohtml "<FONT COLOR="Yellow"><br> $line </br></font>"
            #echohtml "<span style="color:#FF9900;"><br> $line </br></span>"
        fi
		if [ ${#TEMPLINE2} -ne 0 ]; then            
            echohtml "<FONT COLOR="Yellow"><br> $line </br></font>"
        fi
        echo "$line" | grep -q "$ATCERRORLOG"
        if [ "$?" -eq 0 ]; then 
           echohtml "<FONT COLOR="RED"><br> $line </br></font>"
		   TEMPLINE1=$line
		else
			TEMPLINE1=
        fi
		echo "$line" | grep -q "$ATCFAILURELOG"
		if [ "$?" -eq 0 ]; then 
           echohtml "<FONT COLOR="RED"><br> $line </br></font>"
		   TEMPLINE2=$line
		else
			TEMPLINE2=
        fi
                
    done < $ATCUIAUTOLOG

}


#===    Function	===========================================================
#
#	Name:		extractDeviceDataAndSetup
#	Description:	To extract information on devices' IMEI and software signature 
#	Parameter 1:	NA
#	Returns:	NA
#	Notes:		Added by 23048971
#	Created:	2010-06-15
#
#==================================================================================
function extractDeviceDataAndSetup {
  echo "* Extract device information."
  #spankToolDebugLog "extractDeviceDataAndSetup."
  if [ "$EXACTSERIAL" != "" ]; then
    #spankToolDebugLog "extractDeviceDataAndSetup. device specified: $EXACTSERIAL"
    DEVICEUNDERTESTPROPS="DeviceUnderTest_$EXACTSERIAL.txt"

    EXTRACTEDSW=`adb -s $EXACTSERIAL shell getprop > "${LOGSDIR}$DEVICEUNDERTESTPROPS"` 			## EXTRACTS ALL PROPERTIES FROM A DEVICE AND ADDS TO A FILE.
    EXTRACTEDSW=`adb -s $EXACTSERIAL shell getprop | grep ro.build.id | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDHW=`adb -s $EXACTSERIAL shell getprop | grep ro.build.product | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDGMSV=`adb -s $EXACTSERIAL shell getprop | grep ro.com.google.gmsversion | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDCUST=`adb -s $EXACTSERIAL shell getprop | grep ro.semc.version.cust] | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDREV=`adb -s $EXACTSERIAL shell getprop | grep ro.semc.version.cust.revision] | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDHWID=$EXACTSERIAL
    DEVICEIMEI=`python $CURRENTPATH/getIPhoneSubInfo.py -i 1`
    DEVICEPHONENBR=`python $CURRENTPATH/getIPhoneSubInfo.py -i 5`
  else
    #spankToolDebugLog "extractDeviceDataAndSetup. no device specified."
    DEVICEUNDERTESTPROPS="DeviceUnderTest.txt"
    EXTRACTEDSW=`$SH getprop > "${LOGSDIR}$DEVICEUNDERTESTPROPS"` 			## EXTRACTS ALL PROPERTIES FROM A DEVICE AND ADDS TO A FILE.
    EXTRACTEDSW=`$SH getprop | grep ro.build.id | cut -d'[' -f3 | cut -d']' -f1`        
    EXTRACTEDHW=`$SH getprop | grep ro.build.product | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDGMSV=`$SH getprop | grep ro.com.google.gmsversion | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDCUST=`$SH getprop | grep ro.semc.version.cust] | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDREV=`$SH getprop | grep ro.semc.version.cust.revision] | cut -d'[' -f3 | cut -d']' -f1`
    EXTRACTEDHWID=$DEVICENAME
    #DEVICEIMEI=`python $CURRENTPATH/getIPhoneSubInfo.py -i 1`
    #DEVICEPHONENBR=`python $CURRENTPATH/getIPhoneSubInfo.py -i 5`
  fi

  if [ "$DEVICEIMEI" != "" ]; then
    echo "* IMEI found in device properties."
    echo "* IMEI: $DEVICEIMEI "
  else
    echo "* IMEI not found in device properties. "
  fi

  EXTRACTEDUSERID=`whoami`
  EXTRACTEDKERNELID=`uname -mrns`

  #registerUsage									# register usage in the database to keep track of tool usage.

  #XLSFILENAME="${LOGSDIR}spank_xls_$EXTRACTEDHWID.xls"				# Creating spank xls file
  #echoXlsFile "Device.Hw;$EXTRACTEDHW;"
  #echoXlsFile "Device.Sw;$EXTRACTEDSW;"
  #echoXlsFile "Device.Sw-Cust;$EXTRACTEDCUST;"
  #echoXlsFile "Device.Sw-Rev;$EXTRACTEDREV;"
  #echoXlsFile "Device.SIM Phone nbr;$DEVICEPHONENBR;"
  #echoXlsFile "Device.Imei;$DEVICEIMEI;"
  #echoXlsFile "Device.Hwid;$EXTRACTEDHWID;"
  #echoXlsFile "Device.GMS;$EXTRACTEDGMSV;"
  #echoXlsFile "Workstation.User;$EXTRACTEDUSERID;"
  #echoXlsFile "Workstation.Kernel;$EXTRACTEDKERNELID;"
  #echoXlsFile ""
  #echoXlsFile "Seed;Total Time (s);Runtime (s);Result;Source;Details;"		# Add headers to excelfile. For the good looks...

  EVENTSTATISTICSFILE="${LOGSDIR}spank_event_statistics.txt"			# Create a file to fill with Event Statistics raw data.
  CreateSpankHTMLLog								# CREATE A SKELETON HTML FILE (will replace spank_log)
  
  
  #echohtml "<a href=""spank_xls_$EXTRACTEDHWID.xls"">The run in a xls file (importable to excel)</A><br>"
  echohtmlTable "Device.Hw: $EXTRACTEDHW"
  echohtmlTable  "Device.Sw: $EXTRACTEDSW"
  echohtmlTable  "Device.Sw-Cust: $EXTRACTEDCUST"
  echohtmlTable  "Device.Sw-Rev: $EXTRACTEDREV"
  echohtmlTable  "Device.Hwid: $EXTRACTEDHWID"
  
  echohtmldivider

    echo *
    oldIFS=$IFS
    IFS=,
    for i in $JARS
    do  
      echo $i
      echo $SH rm /data/tmp/$i
      `$SH rm /data/tmp/$i`
      echo $ADB push ${CURRENTPATH}/$i /data/tmp/
      `$ADB push ${CURRENTPATH}/$i /data/tmp/`
    done
    IFS=$oldIFS

}

#===    Function	===========================================================
#
#	Name:		echoXlsFile
#	Description:	Printing line to XLS template
#	Parameter 1:	line
#	Returns:	NA.
#	Created:	2010-06-01
#
#==================================================================================
function echoXlsFile {
  echo "$@" >> $XLSFILENAME
  #spankToolDebugLog "echoXlsFile. $@"
}

#===    Function	===========================================================
#
#	Name:           CreateSpankHTMLLog
#	Description:    Create a HTML log
#	Parameter 1:	NA
#	Returns:        NA
#	Created:	2010-02-10
#
#==================================================================================
function CreateSpankHTMLLog {
  echohtml "<html><head>" 
  echohtml "<title>SPANK LOG $EXTRACTEDHW $EXTRACTEDSW</title>" 
  echohtml "<META HTTP-EQUIV="refresh" CONTENT="300">"				# AUTOMATIC REFRESH EVERY 2 MINUTES ( 120 Secs )
  echohtml "</head>"
  echohtml "<body BGCOLOR="LAVENDER">"
  echohtml "<br><BIG><BIG><B>SPANK</BIG></BIG></B><br><br>"
  echohtml "(Automatic refresh every 5 min)"
  echohtml "<br>"  
  echohtml "<a href="$DEVICEUNDERTESTPROPS">The Device under test (properties)</A><br>"
  echohtml "<br>"  
  echohtml "<a href="debug.txt">Debug Information</A><br>"

  echohtml "<br>"
}



while getopts "h:d:f:c:j:" optname 
  do
    case "$optname" in
      "c")
        CLASS="$OPTARG"
        ;;
      "j")        
        JARS="$OPTARG"
        ;;
      "d")									# MULTIPLE DEVICES
        DEVICESERIAL="$OPTARG"
        ;;      
      "f") 									# config file support 
        readConfigFile $OPTARG
        ;;      
      "h") 									# Help menu
	showHelp
        exit
        ;;
      "?")
         exit
        ;;
      ":")
        									# echo "No argument value for option $OPTARG"
        ;;
      *)
        									# Should not occur
        									# echo "Unknown error while processing options"
        ;;
    esac
done

echo $OPTARG
checkAdb
createLogDirectory   								# createLogDirectory
startLogOfDevice
extractDeviceDataAndSetup
UIAUTOSCRIPT="uiautomator runtest $JARS -c $CLASS"
echo $ADB shell $UIAUTOSCRIPT
#prepareJar

`$ADB shell $UIAUTOSCRIPT > $ATCUIAUTOLOG`
parseInformationFromLogFilesAndPresentResult
extractHprofFiles
clean_up


